/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ita.escolaita.ejb;

import br.ita.escolaita.model.entity.Serie;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import static br.ita.escolaita.util.EscolaItaUtil.isBlankOrNull;

/**
 *
 * @author Rafael
 */
@Stateless
public class SerieEjbBean implements SerieEjbLocal {

    @PersistenceContext(unitName = "escolaIta-ejbPU")
    private EntityManager em;

    public void salvar(Serie serie) {
        em.persist(serie);
        em.flush();
    }

    public List<Serie> listarTodos() {
        Query findAllQuery = em.createNamedQuery("serie.findAll");
        List<Serie> series = findAllQuery.getResultList();
        return series;
    }

    public void alterar(Serie serie) {
        try {
            em.merge(serie);
            em.flush();
        } catch (Exception e) {
            System.out.println("Erro " + e);
        }
    }

    public List<Serie> listar(Serie s) {
        StringBuilder sql = new StringBuilder();
        StringBuilder where = new StringBuilder();
        sql.append("SELECT s FROM Serie s ");
        if (!isBlankOrNull(s.getNome())) {
            where.append("WHERE UPPER(s.nome) like UPPER('%").append(s.getNome()).append("%') ");
        }
        Query findAllQuery = em.createQuery(sql.append(where).toString());
        List<Serie> series = findAllQuery.getResultList();
        return series;
    }
}
